import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import type { User } from '@/types'

// 按模块分组定义路由
const authRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/auth/LoginView.vue'),
    meta: { requiresAuth: false, title: '登录' },
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/auth/RegisterView.vue'),
    meta: { requiresAuth: false, title: '注册' },
  },
]

const teacherRoutes: RouteRecordRaw[] = [
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('@/views/teacher/DashboardView.vue'),
    meta: { requiresAuth: true, role: 'teacher', title: '教师工作台' },
  },
  {
    path: '/task/create',
    name: 'taskCreate',
    component: () => import('@/views/teacher/TaskCreateView.vue'),
    meta: { requiresAuth: true, role: 'teacher', title: '创建备课任务' },
  },
  {
    path: '/teaching-design',
    name: 'TeachingDesignList',
    component: () => import('@/views/teacher/CreatePPT.vue'),
    meta: {
      title: 'AI PPT助手',
      requiresAuth: true,
    },
  },
  {
    path: '/teaching-design/:id',
    name: 'teachingDesign',
    component: () => import('@/views/teacher/TeachingDesignView.vue'),
    meta: { requiresAuth: true, role: 'teacher', title: 'AI PPT助手' },
    props: true,
  },
  {
    path: '/resources',
    name: 'Resources',
    component: () => import('@/views/teacher/ResourcesView.vue'),
    meta: {
      title: '教学资源',
      requiresAuth: true,
    },
  },
  {
    path: '/exercises',
    name: 'Exercises',
    component: () => import('@/views/teacher/ExercisesView.vue'),
    meta: {
      title: '习题库',
      requiresAuth: true,
    },
  },
  {
    path: '/exercises/create',
    name: 'ExerciseCreate',
    component: () => import('@/views/teacher/ExerciseCreateView.vue'),
    meta: {
      title: '创建习题',
      requiresAuth: true,
    },
  },
  {
    path: '/analysis',
    name: 'Analysis',
    component: () => import('@/views/teacher/AnalysisView.vue'),
    meta: {
      title: '数据分析',
      requiresAuth: true,
    },
  },
  {
    path: '/history',
    name: 'history',
    component: () => import('@/views/teacher/HistoryView.vue'),
    meta: { requiresAuth: true, role: 'teacher', title: '历史记录' },
  },
  {
    path: '/ai-assistant',
    name: 'AIAssistant',
    component: () => import('@/views/teacher/AIAssistantView.vue'),
    meta: {
      title: 'AI备课助手',
      requiresAuth: true,
      role: 'teacher',
    },
  },
]

const adminRoutes: RouteRecordRaw[] = [
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/views/admin/AdminView.vue'),
    meta: { requiresAuth: true, role: 'admin', title: '管理员控制台' },
  },
]

const commonRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('@/views/common/ProfileView.vue'),
    meta: { requiresAuth: true, title: '个人信息' },
  },
  {
    path: '/settings',
    name: 'settings',
    component: () => import('@/views/common/SettingsView.vue'),
    meta: { requiresAuth: true, title: '系统设置' },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/views/common/NotFoundView.vue'),
    meta: { title: '页面未找到' },
  },
]

// 合并所有路由
const routes: RouteRecordRaw[] = [...authRoutes, ...teacherRoutes, ...adminRoutes, ...commonRoutes]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 定义自定义元数据接口
interface CustomMeta {
  requiresAuth?: boolean
  role?: 'teacher' | 'admin'
  title?: string
}

// 扩展 Vue Router 的 RouteMeta 接口
declare module 'vue-router' {
  interface RouteMeta extends CustomMeta {}
}

// 改进的路由守卫
router.beforeEach(
  (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    // 设置页面标题
    document.title = to.meta.title ? `${to.meta.title} - ClassPrepHub` : 'ClassPrepHub'

    const token = localStorage.getItem('token')
    const userRole = localStorage.getItem('role') as User['role'] | null

    // 未登录但需要认证
    if (to.meta.requiresAuth && !token) {
      next({
        name: 'login',
        query: { redirect: to.fullPath }, // 添加重定向参数，方便登录后返回
      })
      return
    }

    // 角色权限检查
    if (to.meta.role && to.meta.role !== userRole) {
      // 如果是管理员，可以访问教师页面
      if (to.meta.role === 'teacher' && userRole === 'admin') {
        next()
        return
      }

      // 权限不足时重定向
      next({
        name: userRole === 'admin' ? 'admin' : 'dashboard',
        query: { unauthorized: 'true' },
      })
      return
    }

    next()
  },
)

export default router
